package com.wkw.sdemo.handle;

import com.wkw.sdemo.domain.Result;
import com.wkw.sdemo.enums.ResultEnum;
import com.wkw.sdemo.exception.PersonException;
import com.wkw.sdemo.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

//FIXME 20170915 这个类是重点，用来捕获Exception的类

@ControllerAdvice
public class ExceptionHandle {

    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e){
        if(e instanceof PersonException){
            //如果exception是自定义的这个Exception，则根据需要，返回相关异常信息
            PersonException personException = (PersonException) e;
            return ResultUtil.error(personException.getCode(),personException.getMessage());
        }
        //其他异常
        logger.error("[系统异常]{}",e);
        return ResultUtil.error(ResultEnum.UNKONW_ERROR.getCode(),ResultEnum.UNKONW_ERROR.getMsg());
    }
}
